package com.dream.dao.impl;

import com.dream.dao.DomainDao;
import com.dream.domain.Domain;
import org.hibernate.ObjectNotFoundException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ZhongGang
 * Date: 12-12-22
 * Time: 下午3:47
 */
public abstract class DomainDaoImpl extends HibernateDaoSupport implements DomainDao {

    public <T extends Domain> T findByGuid(String guid, Class<T> clazz) {
        String hql = "from " + clazz.getName() + " t where t.guid=?";
        List results = getHibernateTemplate().find(hql, guid);
        if (results.isEmpty()) {
            throw new ObjectNotFoundException(guid, clazz.getName());
        }
        return (T) results.get(0);
    }

    @Override
    public <T extends Domain> List<T> findAll(Class<T> clazz) {
        String hql = "from " + clazz.getName();
        return getHibernateTemplate().find(hql);
    }

    @Override
    public <T extends Domain> void saveOrUpdate(T t) {
        getHibernateTemplate().saveOrUpdate(t);
    }

    @Override
    public <T extends Domain> void delete(T t) {
        getHibernateTemplate().delete(t);
    }
}
